﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Microsoft Corp." file="AzureServiceCredentials.cs">
//   All rights reserved. See License.txt in the project root for license information.
// </copyright>
// 
// --------------------------------------------------------------------------------------------------------------------
namespace AzureManagement
{
    using System;
    using System.Net;
    using System.Security.Cryptography.X509Certificates;

    using Common;

    public class AzureServiceCredentials : IAzureServiceCredentials
    {
        private readonly X509Certificate2 certificate;

        public AzureServiceCredentials(string subscriptionId, string certificateThumbprint)
        {
            if (string.IsNullOrEmpty(subscriptionId))
            {
                throw new ArgumentException("Subscription id must not be null or empty.");
            }

            if (string.IsNullOrEmpty(certificateThumbprint))
            {
                throw new ArgumentException("Certificate thumbprint must not be null or empty.");
            }

            this.SubscriptionId = subscriptionId;

            this.certificate = CertificateHelper.FindCertificate(X509FindType.FindByThumbprint, certificateThumbprint);
            
            if (this.certificate == null)
            {
                throw new ArgumentException("Invalid certificate thumbprint", "certificateThumbprint");
            }
        }

        public string SubscriptionId { get; private set; }

        public WebRequest Sign(WebRequest request)
        {
            var httpWebRequest = request as HttpWebRequest;
            if (httpWebRequest != null)
            {
                httpWebRequest.ClientCertificates.Add(this.certificate);
            }

            return request;
        }
    }
}